<template>
  <div class="study-plan">
    <!-- 添加任务按钮 -->
    <div class="header">
      <h2>学习任务</h2>
      <div class="header-controls">
        <!-- 添加学科筛选器 -->
        <el-select 
          v-model="selectedSubjectId" 
          placeholder="选择学科筛选" 
          clearable
          @change="handleFilterChange"
          style="margin-right: 15px; width: 180px;"
        >
          <el-option 
            v-for="item in subjectList" 
            :key="item.id" 
            :label="item.subject" 
            :value="item.id"
          />
        </el-select>
        <el-button type="primary" @click="showAddDialog">添加任务</el-button>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="plan-list-grid">
      <div class="plan-card" v-for="plan in missionList" :key="plan.id">
        <div class="card-header">
          <span class="mission-title">{{ plan.mission }}</span>
        </div>
        
        <div class="card-content">
          <div class="study-info">
            <div class="info-item">
              <el-icon><Timer /></el-icon>
              <span>学习次数: {{ plan.count || 0 }}次</span>
            </div>
            <div class="info-item">
              <el-icon><Timer /></el-icon>
              <span>总时长: {{ formatTotalTime(plan.totalTime) }}</span>
            </div>
            <div class="info-item" v-if="plan.id === currentMission?.id && isStudying">
              <el-icon><Clock /></el-icon>
              <span>已学习: {{ formatTime(currentTime) }}</span>
            </div>
            <div class="info-item" v-else-if="plan.elapsedTime > 0">
              <el-icon><Clock /></el-icon>
              <span>已学习: {{ formatTime(plan.elapsedTime) }}</span>
            </div>
          </div>
          
          <div class="card-actions">
            <el-button 
              :type="plan.id === currentMission?.id && isStudying ? 'danger' : 'primary'"
              @click="plan.id === currentMission?.id && isStudying ? handleEndStudy() : handleStartStudy(plan)"
              :loading="false"
              class="action-button"
            >
              <el-icon v-if="!(plan.id === currentMission?.id && isStudying)"><VideoPlay /></el-icon>
              <el-icon v-else><VideoPause /></el-icon>
              {{ plan.id === currentMission?.id && isStudying ? '结束学习' : '开始学习' }}
            </el-button>
            <el-button 
              type="danger" 
              plain
              @click="handleDelete(plan)"
              :disabled="plan.id === currentMission?.id && isStudying"
              class="action-button"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty 
      v-if="missionList.length === 0" 
      description="暂无学习任务" 
      :image-size="200"
    >
      <el-button type="primary" @click="showAddDialog">添加任务</el-button>
    </el-empty>

    <!-- 添加任务对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingMission ? '修改学习任务' : '添加学习任务'"
      width="500px"
    >
      <el-form
        ref="missionForm"
        :model="newMission"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="选择学科" prop="subjectId">
          <el-select 
            v-model="newMission.subjectId" 
            placeholder="请选择学科"
            @change="handleSubjectChange"
            style="width: 100%"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.subject"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学习内容" prop="mission">
          <el-input v-model="newMission.mission" placeholder="请输入学习内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddMission">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 学习时钟弹窗 -->
    <el-dialog
      v-model="clockDialogVisible"
      title="正在学习中"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      class="study-clock-dialog"
    >
      <div class="clock-container">
        <div class="clock-header">
          <div class="mission-info">
            <el-icon class="mission-icon"><Reading /></el-icon>
            <span class="mission-text">{{ currentMission?.mission }}</span>
          </div>
          <el-tag type="success" class="status-tag" effect="dark">正在学习中</el-tag>
        </div>

        <div class="clock-body">
          <div class="time-display">
            <div class="time-blocks">
              <div class="time-block">
                <div class="time-value">{{ Math.floor(currentTime / 3600).toString().padStart(2, '0') }}</div>
                <div class="time-label">小时</div>
              </div>
              <div class="time-separator">:</div>
              <div class="time-block">
                <div class="time-value">{{ Math.floor((currentTime % 3600) / 60).toString().padStart(2, '0') }}</div>
                <div class="time-label">分钟</div>
              </div>
              <div class="time-separator">:</div>
              <div class="time-block">
                <div class="time-value">{{ (currentTime % 60).toString().padStart(2, '0') }}</div>
                <div class="time-label">秒</div>
              </div>
            </div>
          </div>
        </div>

        <div class="clock-footer">
          <div class="study-stats">
            <div class="stat-item">
              <el-icon><Timer /></el-icon>
              <span>今日学习：2小时30分</span>
            </div>
            <div class="stat-item">
              <el-icon><Trophy /></el-icon>
              <span>连续学习：3天</span>
            </div>
          </div>
          <el-button 
            type="danger" 
            size="large" 
            class="end-button"
            @click="handleEndStudy"
          >
            <el-icon><CircleClose /></el-icon>
            结束学习
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { VideoPause, Timer, Clock, Delete, Reading, Trophy, CircleClose, VideoPlay } from '@element-plus/icons-vue'
import axios from 'axios'

const dialogVisible = ref(false)
const clockDialogVisible = ref(false)
const missionList = ref([])
const timer = ref(null)
const clockTimer = ref(null)
const editingMission = ref(null)
const currentMission = ref(null)
const currentTime = ref(0)
const currentStudyId = ref(null)

// 记录开始学习的时间戳，用于更精确的计时
const startTimestamp = ref(0)

// 学习状态
const isStudying = ref(false)

// 学习状态存储键
const STUDY_STATE_KEY = 'study_state'

// 防恭屏相关变量
const noSleepVideoEl = ref(null)
const keepAwakeActive = ref(false)

// 学科列表
const subjectList = ref([])

// 选中的学科ID，用于筛选
const selectedSubjectId = ref('')

// 新任务表单
const newMission = ref({
  subjectId: '',
  subject: '',
  mission: ''
})

// 表单验证规则
const rules = {
  subjectId: [{ required: true, message: '请选择学科', trigger: 'change' }],
  mission: [{ required: true, message: '请输入学习内容', trigger: 'blur' }]
}

// 获取学科列表
const fetchSubjectList = async () => {
  try {
    const response = await axios.get('/api/subject/list')
    if (response.data.code === '200') {
      let arr = response.data.data?.data
      if (!Array.isArray(arr)) arr = []
      subjectList.value = arr
    }
  } catch (error) {
    console.error('获取学科列表失败:', error)
    ElMessage.error('获取学科列表失败')
  }
}

// 处理学科选择变化
const handleSubjectChange = (value) => {
  const selectedSubject = subjectList.value.find(item => item.id === value)
  if (selectedSubject) {
    newMission.value.subject = selectedSubject.subject
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogVisible.value = true
  editingMission.value = null
  newMission.value = {
    subjectId: '',
    subject: '',
    mission: ''
  }
}

// 格式化时间
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const remainingSeconds = seconds % 60
  
  const parts = []
  if (hours > 0) parts.push(`${hours}小时`)
  if (minutes > 0) parts.push(`${minutes}分钟`)
  if (remainingSeconds > 0) parts.push(`${remainingSeconds}秒`)
  
  return parts.join('')
}

// 格式化时间值，确保两位数显示
const formatTimeValue = (value) => {
  return String(value || 0).padStart(2, '0')
}

// 添加或修改任务
const handleAddMission = async () => {
  try {
    const response = await axios.post('/api/studyMission/add', {
      id: editingMission.value?.id,
      subjectId: newMission.value.subjectId,
      subject: newMission.value.subject,
      mission: newMission.value.mission
    })
    
    if (response.data.code === '200') {
      ElMessage.success(editingMission.value ? '修改任务成功' : '添加任务成功')
      dialogVisible.value = false
      fetchMissionList()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 处理学科筛选变化
const handleFilterChange = () => {
  fetchMissionList()
}

// 获取任务列表
const fetchMissionList = async () => {
  try {
    // 构建请求参数
    const params = {}
    if (selectedSubjectId.value) {
      params.subjectId = selectedSubjectId.value
    }
    
    // 发起请求，带上筛选参数
    const response = await axios.get('/api/studyMission/list1', { params })
    
    if (response.data.code === '200') {
      missionList.value = response.data.data.data || []
      console.log('获取任务列表成功:', missionList.value)
    } else {
      ElMessage.error(response.data.message || '获取任务列表失败')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  }
}

// 删除任务
const handleDelete = async (mission) => {
  try {
    await ElMessageBox.confirm('确定要删除这个学习任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`/api/studyMission/${mission.id}/delete`)
    if (response.data.code === '200') {
      ElMessage.success('删除成功')
      fetchMissionList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 开始学习
const handleStartStudy = async (mission) => {
  console.log('handleStartStudy', mission.id)
  
  // 如果已经有正在进行的学习，先结束它
  if (isStudying.value && currentMission.value) {
    await handleEndStudy()
  }
  
  try {
    // 在API调用前先设置状态，使界面立即响应
    currentMission.value = mission
    currentTime.value = 0
    isStudying.value = true
    
    // 记录开始时间
    startTimestamp.value = Date.now()
    
    // 启动计时器
    startTimer(mission)
    
    // 显示通知
    ElNotification({
      title: '学习已开始',
      message: `正在学习: ${mission.mission}`,
      type: 'success',
      duration: 3000
    })
    
    // 调用开始学习接口
    const response = await axios.post('/api/study/add', {
      missionId: mission.id
    })
    
    if (response.data.code === '200') {
      // 更新学习ID
      currentStudyId.value = response.data.data.id
      
      // 将学习状态保存到localStorage
      saveStudyState()
      
      // 刷新任务列表，显示最新的学习时长
      fetchMissionList()
      
      // 显示学习状态在页面上
      clockDialogVisible.value = false
    } else {
      ElMessage.error(response.data.message || '开始学习失败')
    }
  } catch (error) {
    console.error('开始学习失败:', error)
    ElMessage.error('开始学习失败')
  }
}

// 处理学习动作（开始/结束）- 保留这个函数以便兼容其他可能调用它的代码
const handleStudyAction = async (mission) => {
  console.log('handleStudyAction', mission.id, currentMission?.id, isStudying.value)
  
  // 判断是开始学习还是结束学习
  const isEndingStudy = mission.id === currentMission?.id && isStudying.value
  
  if (!isEndingStudy) {
    // 开始学习
    handleStartStudy(mission)
  } else {
    // 结束学习
    handleEndStudy()
  }
}

// 启动计时器
const startTimer = (mission) => {
  // 清除现有计时器
  if (clockTimer.value) {
    clearInterval(clockTimer.value)
  }
  
  // 使用更可靠的计时方法，基于真实时间差值
  clockTimer.value = setInterval(() => {
    const now = Date.now()
    const elapsedSeconds = Math.floor((now - startTimestamp.value) / 1000)
    currentTime.value = elapsedSeconds
    
    // 更新当前任务的学习时长
    if (currentMission.value && currentMission.value.id === mission.id) {
      // 在missionList中找到当前任务并更新它的学习时长
      const missionIndex = missionList.value.findIndex(m => m.id === mission.id)
      if (missionIndex !== -1) {
        // 直接修改列表中的对象，触发响应式更新
        missionList.value[missionIndex].elapsedTime = elapsedSeconds
      }
    }
    
    // 定期保存学习状态到localStorage并刷新任务列表
    if (elapsedSeconds % 10 === 0) { // 每10秒保存一次并刷新列表
      saveStudyState()
      fetchMissionList() // 定期刷新任务列表，确保显示最新的学习时长
    }
  }, 1000)
}

// 结束学习
const handleEndStudy = async () => {
  console.log('handleEndStudy', isStudying.value, currentMission.value, currentStudyId.value)
  
  // 如果没有正在进行的学习，直接返回
  if (!isStudying.value || !currentMission.value || !currentStudyId.value) {
    console.log('没有正在进行的学习')
    return;
  }
  
  if (clockTimer.value) {
    clearInterval(clockTimer.value)
    clockTimer.value = null
  }
  
  // 停止防恭屏
  stopPreventSleep()
  
  try {
    // 计算学习时间
    const hours = Math.floor(currentTime.value / 3600)
    const minutes = Math.floor((currentTime.value % 3600) / 60)
    const seconds = currentTime.value % 60
    
    // 格式化总时间
    const formattedTotalTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    
    console.log('结束学习参数', {
      id: currentStudyId.value,
      missionId: currentMission.value.id,
      hour: hours,
      minute: minutes,
      second: seconds,
      endTime: formatDate(new Date()),
      totalTime: formattedTotalTime
    })
    
    // 调用结束学习接口 - 使用与开始学习相同的端点，但传递不同的参数
    const response = await axios.post('/api/study/add', {
      id: currentStudyId.value,
      missionId: currentMission.value.id,
      hour: hours,
      minute: minutes,
      second: seconds,
      endTime: formatDate(new Date()),
      totalTime: formattedTotalTime
    })
    
    if (response.data.code === '200') {
      // 成功结束学习
      ElMessage.success('学习已结束，已记录学习时间')
      
      // 重置状态
      isStudying.value = false
      clockDialogVisible.value = false
      
      // 清除存储的学习状态
      clearStudyState()
      
      // 刷新任务列表
      await fetchMissionList()
      
      // 重置当前任务
      const tempMissionId = currentMission.value.id
      currentMission.value = null
      currentStudyId.value = null
      currentTime.value = 0
      
      // 显示通知
      ElNotification({
        title: '学习已结束',
        message: `学习时间: ${hours}时${minutes}分${seconds}秒`,
        type: 'success',
        duration: 5000
      })
    } else {
      ElMessage.error(response.data.message || '结束学习失败')
    }
  } catch (error) {
    console.error('结束学习失败:', error)
    ElMessage.error('结束学习失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 格式化总时长
function formatTotalTime(timeStr) {
  if (!timeStr) return '0秒'
  const [h, m, s] = timeStr.split(':').map(Number)
  let result = ''
  if (h) result += `${h}小时`
  if (m) result += `${m}分`
  if (s) result += `${s}秒`
  return result || '0秒'
}

// 组件挂载时获取任务列表
onMounted(() => {
  fetchMissionList()
  fetchSubjectList() // 获取学科列表
})

// 组件卸载时清理资源
onUnmounted(() => {
  try {
    console.log('组件卸载，清理资源')
    
    // 如果还在学习，保存状态
    if (isStudying.value && currentMission.value) {
      // 计算当前学习时间
      const now = Date.now()
      const elapsedSeconds = Math.floor((now - startTimestamp.value) / 1000)
      currentTime.value = elapsedSeconds
      
      // 保存学习状态到localStorage
      saveStudyState()
      console.log('已保存学习状态，学习时间：', elapsedSeconds)
    }
    
    // 清理定时器
    if (clockTimer.value) {
      clearInterval(clockTimer.value)
      clockTimer.value = null
    }
    
    // 清理防恭屏视频
    if (typeof stopPreventSleep === 'function') {
      stopPreventSleep()
    }
    
    if (noSleepVideoEl && noSleepVideoEl.value && document.body.contains(noSleepVideoEl.value)) {
      document.body.removeChild(noSleepVideoEl.value)
      noSleepVideoEl.value = null
    }
  } catch (error) {
    console.error('组件卸载时出错:', error)
  }
})
// 防止系统恭屏
const preventSleep = () => {
  try {
    if (!noSleepVideoEl.value) {
      // 创建一个不可见的视频元素
      const video = document.createElement('video')
      video.setAttribute('loop', '')
      video.setAttribute('playsinline', '')
      video.setAttribute('muted', '')
      video.setAttribute('width', '1')
      video.setAttribute('height', '1')
      video.style.position = 'absolute'
      video.style.opacity = '0.01'
      video.style.pointerEvents = 'none'
      video.style.zIndex = '-1'
      
      // 创建一个空白视频源
      const source = document.createElement('source')
      source.setAttribute('src', 'data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAA+NtZGF0AAACrQYF//+p3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE1NSByMjkwMSA3ZDBmZjIyIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxOCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTMgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAgZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz0zIGJfcHlyYW1pZD0yIGJfYWRhcHQ9MSBiX2JpYXM9MCBkaXJlY3Q9MSB3ZWlnaHRiPTEgb3Blbl9nb3A9MCB3ZWlnaHRwPTIga2V5aW50PTI1MCBrZXlpbnRfbWluPTEgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD00MCByYz1jcmYgbWJ0cmVlPTEgY3JmPTI4LjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAAwZYiEAD//8m+P5OXfBeLGOfKE3xkODvFZuBflHv/+VwJIta6cbpIo4ABLoKBaYTkTAAAC7m1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAPoAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIYdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAPoAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAACgAAAAWgAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAD6AAAAAAAAQAAAAABkG1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAEAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAATttaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAD7c3RibAAAAJdzdHNkAAAAAAAAAAEAAACHYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAACgAFoASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAADFhdmNDAWQACv/hABhnZAAKrNlCjfkhAAADAAEAAAMAAg8SJZYBAAZo6+JLIsAAAAAYc3R0cwAAAAAAAAABAAAAAgAAQAAAAAAUc3RzcwAAAAAAAAABAAAAAQAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAcc3RzegAAAAAAAAAAAAAAAgAAAE0AAAAMAAAAFHN0Y28AAAAAAAAAAQAAADAAAABidWR0YQAAAFptZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAAC1pbHN0AAAAJal0b28AAAAdZGF0YQAAAAEAAAAATGF2ZjU4LjI5LjEwMA==')
      source.setAttribute('type', 'video/mp4')
      video.appendChild(source)
      
      // 添加到DOM并播放
      document.body.appendChild(video)
      video.play()
        .then(() => {
          keepAwakeActive.value = true
          noSleepVideoEl.value = video
          console.log('防恭屏已启动')
        })
        .catch(err => {
          console.error('防恭屏启动失败:', err)
        })
    } else if (noSleepVideoEl.value && !keepAwakeActive.value) {
      // 如果已经创建但没有激活，尝试重新播放
      noSleepVideoEl.value.play()
        .then(() => {
          keepAwakeActive.value = true
          console.log('防恭屏已重新启动')
        })
        .catch(err => {
          console.error('防恭屏重新启动失败:', err)
        })
    }
  } catch (error) {
    console.error('防恭屏功能错误:', error)
  }
}

// 停止防恭屏
const stopPreventSleep = () => {
  try {
    if (noSleepVideoEl.value && keepAwakeActive.value) {
      noSleepVideoEl.value.pause()
      keepAwakeActive.value = false
      console.log('防恭屏已停止')
    }
  } catch (error) {
    console.error('停止防恭屏功能错误:', error)
  }
}

// 组件卸载时清理
// 注意：这个钩子函数已经合并到前面的onUnmounted中
// 保存学习状态到localStorage
const saveStudyState = () => {
  if (currentMission.value && isStudying.value) {
    const studyState = {
      missionId: currentMission.value.id,
      missionName: currentMission.value.mission,
      startTimestamp: startTimestamp.value,
      currentTime: currentTime.value,
      studyId: currentStudyId.value,
      lastUpdated: Date.now()
    }
    localStorage.setItem(STUDY_STATE_KEY, JSON.stringify(studyState))
  }
}

// 清除存储的学习状态
const clearStudyState = () => {
  localStorage.removeItem(STUDY_STATE_KEY)
}

// 从 localStorage 恢复学习状态
const restoreStudyState = async () => {
  try {
    const savedState = localStorage.getItem(STUDY_STATE_KEY)
    if (savedState) {
      const studyState = JSON.parse(savedState)
      
      // 检查是否是当天的学习记录
      const now = new Date()
      const lastUpdated = new Date(studyState.lastUpdated)
      const isSameDay = now.getDate() === lastUpdated.getDate() && 
                       now.getMonth() === lastUpdated.getMonth() && 
                       now.getFullYear() === lastUpdated.getFullYear()
      
      if (isSameDay) {
        // 获取任务信息
        await fetchMissionList()
        
        // 找到对应的任务
        const mission = missionList.value.find(m => m.id === studyState.missionId)
        
        if (mission) {
          // 恢复学习状态
          currentMission.value = mission
          startTimestamp.value = studyState.startTimestamp
          currentStudyId.value = studyState.studyId
          isStudying.value = true
          mission.status = 'in_progress'
          
          // 计算当前已学习时间
          const now = Date.now()
          const elapsedSeconds = Math.floor((now - startTimestamp.value) / 1000)
          currentTime.value = elapsedSeconds
          mission.elapsedTime = elapsedSeconds
          
          // 重新启动计时器
          startTimer(mission)
          
          // 显示通知
          ElNotification({
            title: '恢复学习状态',
            message: `继续学习: ${mission.mission}`,
            type: 'info',
            duration: 5000
          })
          
          return true
        }
      } else {
        // 如果不是当天的学习记录，清除存储
        clearStudyState()
      }
    }
  } catch (error) {
    console.error('恢复学习状态失败:', error)
    clearStudyState()
  }
  
  return false
}

// 页面加载时恢复学习状态
onMounted(async () => {
  await fetchSubjectList()
  await fetchMissionList()
  
  // 尝试恢复学习状态
  await restoreStudyState()
})

// 注意：这个钩子函数已经合并到前面的onUnmounted中

// 监听页面可见性变化
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible' && isStudying.value) {
    // 页面变为可见时，更新计时器
    if (currentMission.value) {
      const now = Date.now()
      const elapsedSeconds = Math.floor((now - startTimestamp.value) / 1000)
      currentTime.value = elapsedSeconds
      currentMission.value.elapsedTime = elapsedSeconds
    }
  }
})

// 添加页面关闭前的保存逻辑
window.addEventListener('beforeunload', () => {
  if (isStudying.value) {
    saveStudyState()
  }
})
</script>

<style scoped>
.study-plan {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: linear-gradient(135deg, #409EFF 0%, #85c5ff 100%);
  padding: 20px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.15);
}

.header-controls {
  display: flex;
  align-items: center;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
}

.header .el-button {
  background: white;
  border: none;
  color: #409EFF;
  font-weight: 500;
  padding: 12px 24px;
  height: auto;
  transition: all 0.3s ease;
}

.header .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 255, 255, 0.2);
}

.plan-list-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
  margin-top: 20px;
}

.plan-card {
  height: 100%;
  transition: all 0.3s ease;
  border: none;
  border-radius: 16px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.plan-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  background: linear-gradient(135deg, #409EFF 0%, #85c5ff 100%);
  color: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.card-header::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 100%);
  pointer-events: none;
}

.mission-title {
  font-size: 18px;
  font-weight: 500;
  flex: 1;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.card-content {
  padding: 24px;
  background: white;
}

.study-info {
  margin-bottom: 24px;
  background: #f8fafc;
  padding: 16px;
  border-radius: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .el-icon {
  font-size: 18px;
  color: #409EFF;
  background: rgba(64, 158, 255, 0.1);
  padding: 8px;
  border-radius: 8px;
}

.card-actions {
  display: flex;
  gap: 12px;
}

.action-button {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  border-radius: 10px;
  padding: 12px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-2px);
}

.action-button .el-icon {
  font-size: 18px;
}

.el-empty {
  padding: 60px;
  background: white;
  border-radius: 16px;
  margin-top: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.study-clock-dialog {
  :deep(.el-dialog) {
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
  }
  :deep(.el-dialog__header) {
    display: none;
  }
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.clock-container {
  background: #ffffff;
  color: #2c3e50;
}

.clock-header {
  padding: 28px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #409EFF 0%, #85c5ff 100%);
  border-bottom: none;
  color: white;
}

.mission-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.mission-icon {
  font-size: 28px;
  color: white;
  background: rgba(255, 255, 255, 0.2);
  padding: 12px;
  border-radius: 12px;
}

.mission-text {
  font-size: 20px;
  font-weight: 500;
  color: white;
}

.clock-body {
  padding: 32px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.time-display {
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
  padding: 32px 48px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.time-blocks {
  display: flex;
  align-items: center;
  gap: 16px;
}

.time-block {
  text-align: center;
}

.time-value {
  font-size: 64px;
  font-weight: 600;
  color: #1a1f36;
  line-height: 1;
  font-variant-numeric: tabular-nums;
}

.time-label {
  margin-top: 8px;
  font-size: 14px;
  color: #697386;
}

.time-separator {
  font-size: 48px;
  font-weight: 600;
  color: #1a1f36;
  margin-top: -20px;
}

@media (max-width: 640px) {
  .time-display {
    padding: 24px;
  }

  .time-value {
    font-size: 48px;
  }

  .time-separator {
    font-size: 36px;
    margin-top: -12px;
  }
}

.clock-footer {
  padding: 28px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8fafc;
  border-top: 1px solid #edf2f7;
}

.study-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #475569;
  font-weight: 500;
}

.stat-item .el-icon {
  font-size: 20px;
  color: #409EFF;
  background: rgba(64, 158, 255, 0.1);
  padding: 8px;
  border-radius: 8px;
}

.end-button {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 32px;
  border-radius: 30px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  border: none;
  color: white;
}

.end-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(239, 68, 68, 0.2);
}

.end-button:active {
  transform: translateY(0);
}
</style> 